package org.shoukaiseki.web;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 **/
public class WebDriverMainAsync {


    public static void main(String[] args) throws InterruptedException, IOException {

        ClassLoader classLoader = WebDriverMainAsync.class.getClassLoader();
        InputStream stencilsetStream = classLoader.getResourceAsStream("search_async.js");
        String searchJs = IOUtils.toString(stencilsetStream, "utf-8");
        System.out.println(searchJs);


        System.setProperty ( "webdriver.firefox.bin" , "C:/Program Files (x86)/Mozilla Firefox/firefox.exe" );
        System.setProperty ( "webdriver.gecko.driver" , "win/x32/geckodriver.exe" );

//        ProfilesIni pi = new ProfilesIni();
//        FirefoxProfile profile = pi.getProfile("selenium");
//        FirefoxOptions options = new FirefoxOptions();
//        options.setProfile(profile);
//        WebDriver driver = new FirefoxDriver(options);
        WebDriver driver = new FirefoxDriver();

        //不兼容 selenium3
//        HtmlUnitDriver  driver = new HtmlUnitDriver(false);
//        ((HtmlUnitDriver) driver).setJavascriptEnabled(true);

        driver.manage().timeouts().setScriptTimeout(99999, TimeUnit.HOURS);
        driver.manage().timeouts().implicitlyWait(99999, TimeUnit.HOURS);
        driver.manage().timeouts().pageLoadTimeout(99999, TimeUnit.HOURS);
//        WebDriver driver = new ChromeDriver();
        String url = "https://github.com/login";
        url="https://ccare.crm.huawei.com";
//        url="https://www.baidu.com";
        String loginUsername="xxxxxxxx";
        String loginPassword="xxxxx";

        driver.get(url);
        WebElement elemUsername = driver.findElement(By.id("uid")); //获取用户名框
        WebElement elemPassword = driver.findElement(By.id("password")); //获取密码框
        //登录按钮
        By loginButton = By.cssSelector("input[class='login_submit_pwd']");
        //也可以用这个
//       loginButton=By.className("login_submit_pwd");
        WebElement btn = driver.findElement(loginButton);    //获取点击登陆按钮。

        elemUsername.sendKeys(loginUsername);
        elemPassword.sendKeys(loginPassword);
        // 点击行为；
        btn.submit();

        //查询点击元素
        By flyoutAnchorArrow = By.className("flyoutAnchorArrow");

        System.out.println("-------------CurrentUrl="+driver.getCurrentUrl());

        WebDriverWait wait = new WebDriverWait(driver, 6000);
        wait.until(ExpectedConditions.presenceOfElementLocated(flyoutAnchorArrow));

        //点击查询
        WebElement searchs=driver.findElement(flyoutAnchorArrow);
        searchs.click();


        //权益查询元素

        By rightsrightSearchText = By.linkText("权益查询");

//        By rightsrightSearch = By.className("ms-crm-CommandBar-Menu");
//        rightsrightSearch =By.cssSelector("a[class='ms-crm-Menu-Label']");
        wait.until(ExpectedConditions.presenceOfElementLocated(rightsrightSearchText));
        //点击 权益查询
        WebElement rightsrightSearchEle=driver.findElement(rightsrightSearchText);
        System.out.println(rightsrightSearchEle.getTagName());
        System.out.println(rightsrightSearchEle.getLocation());
        System.out.println(rightsrightSearchEle.getRect());
        System.out.println(rightsrightSearchEle.getSize());
        System.out.println(rightsrightSearchEle.getText());

        //权益查询点击
        rightsrightSearchEle.click();

        //SN输入框id  imeisn
        //查询按钮id  Select


        Set<String> childids = driver.getWindowHandles();

        for(String s:childids){
            if(driver.switchTo().window(s).getTitle().contains("rightsrightsearch")){
                driver= driver.switchTo().window(s);
                String titleChild = driver.getTitle();
                System.out.println("name:"+titleChild);
                break;
            }
        }

        WebDriver rightsrightsearch = driver;
        System.out.println(driver.getCurrentUrl());

        By imeisn = By.id("imeisn");
        By selectButton = By.id("Select");
        WebDriverWait wait2 = new WebDriverWait(driver, 6000);
        WebElement until = wait2.until(ExpectedConditions.presenceOfElementLocated(imeisn));
        System.out.println("until="+until.getTagName());

// 用js判断页面加载完毕，返回complete
        System.out.println("readyState:" + ((JavascriptExecutor )driver).executeScript("return document.readyState").toString());
        while (!"complete".equals(((JavascriptExecutor )driver).executeScript("return document.readyState"))){
            try {
                Thread.sleep(100);
            }catch (Exception e){

            }
        }
        System.out.println("readyState:" + ((JavascriptExecutor )driver).executeScript("return document.readyState").toString());

        System.out.println("-----------title="+driver.getTitle());
        WebElement imeisnEle = rightsrightsearch.findElement(imeisn);
        WebElement selectButtonEle = rightsrightsearch.findElement(selectButton);
        imeisnEle.sendKeys("868802049323827");
//        selectButtonEle.click();
        System.out.println("selectButtonEle.text="+selectButtonEle.getText());

//        Thread.sleep(30000L);




        WebDriverWait executeJSwait = new WebDriverWait(driver, 999999,2000);

        FileReader fr = new FileReader("haw/imei.txt");
        BufferedReader bf = new BufferedReader(fr);
        String sn;
        long startTime=System.currentTimeMillis();
        int i=0;

        List<String> imeisns= Lists.newArrayList();

        // 按行读取字符串
        while ((sn = bf.readLine()) != null) {
            i++;
            if(!imeisns.contains(sn)){
                imeisns.add(sn);
            }
            if(i%100!=0){
                continue;
            }
            StringBuilder jsImeisns=new StringBuilder("var imeisnAsus = new Array();");
            int jsIndex=0;
            for (String temp : imeisns) {
                jsImeisns.append("imeisnAsus[").append(jsIndex).append("]='").append(temp).append("';");
                jsIndex++;
            }
            StringBuilder sb=new StringBuilder(jsImeisns).append(searchJs);

            Object o ;
            o=((RemoteWebDriver) driver).executeScript(sb.toString());
//            int asusLength;
//            do {
//                Thread.sleep(100);
//                asusLength=(int)((RemoteWebDriver) driver).executeScript("return asus.length;");
//            }while (asusLength<imeisns.size());
//            o=((RemoteWebDriver) driver).executeScript("return asus.length;");
//            Object o=executeJSwait.until(webDriver -> {
//                Object o1 ;
//                 ((RemoteWebDriver) webDriver).executeAsyncScript(sb.toString());
//                o1=((RemoteWebDriver) webDriver).executeScript("return asus;");
//                return o1;
//            });
//        Object asus=((RemoteWebDriver) driver).executeScript(searchJs);
//        System.out.println("asus="+asus);

            System.out.println(o.getClass());
            System.out.println("o="+ JSONObject.toJSONString(imeisns));
            System.out.println("o="+ JSONObject.toJSONString(o));
            //170804  100个
            //198842  100个
           if(i>=100){
               break;
           }
            imeisns= Lists.newArrayList();
        }
        bf.close();

        long endTime=System.currentTimeMillis();

        long l = endTime - startTime;

        System.out.println("l="+(l/1000));

    }

}
